# -*- coding: utf-8 -*-
import ast
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1024': {
        # 郎朗支付 支付宝H5订 2.9%  50 100 200 300 400 500 600 700 800 900 1000 1500 2000 3000 4000 5000 zs
        'API_KEY': '44b18fdaaa4d4e53bc5916cdda745f2c',
        'gateway': 'http://openapi.gotozf.com/v1/pay/create',
        # 'query_gateway': 'http://openapi.gotozf.com',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += '%s' % key
    return _gen_sign(s)


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("langlangpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 二维码支付：erwm，网银支付：wyzf，微信H5：wxh5，支付宝红包：zfbhb，支付宝H5：zfbh5，支付宝二维码：zfberwm，微信二维码：wxerwm
def _get_pay_type(service):
    if service == 'alipay_h5':
        return 'zfbh5'
    return 'zfbh5'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('uid', app_id),
        ('price', '%.2f' % pay_amount),
        ('service', 'service.business.payment'),
        ('trade_type', _get_pay_type(service)),
        ('notify_url', '{}/pay/api/{}/langlangpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        (
            'return_url',
            '{}/pay/api/{}/langlangpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('orderid', str(pay.id)),
        ('orderuid', str(pay.user_id)),
        ('goodsname', 'LLpay'),
        # ('bankcode', ''),
        # ('cardtype', ''),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("langlangpay create: %s, order_id is: %s", json.dumps(parameter_dict), str(pay.id))
    headers = {"Content-type": "application/x-www-form-urlencoded"}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('langlangpay create rsp, %s', response.text)
    verify_sign(json.loads(response.text)['data'], api_key)
    return {'charge_info': json.loads(response.text)['data']['qrcode']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    d = dict(request.POST.iteritems())['data']
    data = ast.literal_eval(d)
    _LOGGER.info("langlangpay notify data is: %s, pay_id is: %s", data, data['m_orderno'])
    verify_sign(data, api_key)
    pay_id = data['m_orderno']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('langlangpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = ''
    total_fee = float(data['amount'])
    trade_no = str(data['p_orderno'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    _LOGGER.info('langlangpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
    order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
    # async notify
    async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass
